// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
  })

// 云函数入口函数 --添加健康记录
exports.main = async (event, context) => {
    console.log("添加健康记录[传入参数为]:", event)
    const db = cloud.database()

    //获取年月
    let ymd = getNowFormatDate()
    if(event.ymd){
        ymd = event.ymd
    }
    let month = getNowFormatMonth()
    if(event.ym){
        month = event.ym
    }

    let id = event.userInfo.openId +"_"+ ymd
    let data = {
        openId: event.userInfo.openId,
        appId: event.userInfo.appId,
        time: ymd,
        month: month,
        pos: event.pos,
        weight: event.weight
    }
    console.log("添加健康记录[data]:", data)

    const result = await db.collection('health_rdl').doc(id).set({
        data:data,
    }).then(res => {
        console.log("保存健康记录返回[res]", res)
        return res
    })

    return result
}

function getNowFormatDate() {
    let date = new Date();
    let sep = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    let currentDate = year + sep + month + sep + strDate;
    return currentDate;
}

function getNowFormatMonth() {
    let date = new Date();
    let sep = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    let currentDate = year + sep + month
    return currentDate;
}


